package org.gikolet.ch2.android.widget;

import java.io.IOException;
import java.util.List;

import org.gikolet.ch2.data.Res;
import org.gikolet.ch2.data.ThreadHeader;
import org.gikolet.ch2.logic.ResesLogic;

import roboguice.inject.ContextScoped;
import android.content.Context;
import android.text.SpannableStringBuilder;

import com.google.inject.Inject;

@ContextScoped
public class ResTextView extends DynamicTextView {

	private ThreadHeader threadHeader;

	@Inject
	private ResesLogic resesLogic;

	private ResSpannableParser resSpannableParser = new ResSpannableParser();

	private int beforePosition = -1;

	private boolean first = true;

	private SpannableStringBuilder text;

	@Inject
	public ResTextView(Context context) {
		super(context);

		this.text = getText();
		this.resSpannableParser = new ResSpannableParser();

		this.resSpannableParser.setOnResClickListener(new OnResClickListener() {
			public void onResNoClick(int resNo) {
				ResTextView.this.onResNoClick(resNo);
			}

			public void onResAnchorClick(int resNoStart, int resNoEnd) {
				ResTextView.this.onResAnchorClick(resNoStart, resNoEnd);
			}
		});

		setFocusable(true);
		setClickable(true);
		setLongClickable(true);
	}

	public void onResNoClick(int resNo) {
		System.out.println("no:" + resNo);
	}

	public void onResAnchorClick(int resNoStart, int resNoEnd) {
		// setSelection(resNoStart - 1);
	}

	public void setThreadHeader(ThreadHeader threadHeader) {
		this.threadHeader = (threadHeader != null) ? new ThreadHeader(
				threadHeader) : null;

		this.text.clear();

		SpannableStringBuilder tmpText = new SpannableStringBuilder();
		try {
			List<Res> reses = this.resesLogic.getReses(this.threadHeader);
			for (int i = 0; i < reses.size(); i++) {
				this.resSpannableParser.appendSpannable(tmpText, i + 1,
						reses.get(i));
			}
			this.text.append(tmpText);
			invalidate();

		} catch (IOException e) {
			e.printStackTrace();
			// TODO ここどうしようか？
			// でも原理上通信は無いはず？
		}
	}

	public ThreadHeader getThreadHeader() {
		return new ThreadHeader(this.threadHeader);
	}
}
